/**
 * yiqihao(一起好商务股份有限公司) copyright 
 */
package com.p2p.funds.web.controller;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.activemq.command.ActiveMQTopic;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.view.RedirectView;

import com.p2p.base.annotation.LoginNeedless;
import com.p2p.base.constents.InnerAccountConsts;
import com.p2p.base.model.Money;
import com.p2p.base.model.P2PRecharge;
import com.p2p.base.service.ProducerService;
import com.p2p.base.util.MD5Util;
import com.p2p.base.web.controller.BaseController;
import com.p2p.funds.model.BaofuConfig;
import com.p2p.funds.model.FundsConfig;
import com.p2p.funds.service.P2PRechargeReturnService;
import com.p2p.funds.service.P2PRechargeService;
import com.p2p.trans.client.facade.AccountTransFacade;
import com.p2p.trans.client.model.TransInfo;
import com.p2p.trans.client.result.AccountTransResult;

/**
 *
 * @author leiruiqi@yiqihao.com
 *
 * 2015年2月4日 下午2:24:01
 */
@RequestMapping("/baofu")
@Controller
public class BaofuPaymenController extends BaseController{

	private static final Logger logger = LoggerFactory
			.getLogger(BaofuPaymenController.class);

	@Resource
	private P2PRechargeService p2pRechargeService;

	//@Resource
	//private P2PRechargeReturnService p2pRechargeReturnService;

	@Resource
	private AccountTransFacade accountTransFacade;

	/*@Resource
	private UserQueryFacade remoteUserQueryFacade;*/

	//private final static String ENCRYPTIONKEY = "shengfutongSHENGFUTONGtest";

	private static DateFormat dateformat = new SimpleDateFormat(
			"yyyyMMddHHmmss");
	//private String sendTime = dateformat.format(Calendar.getInstance()
		//	.getTime());
	//private String orderNO = "1237929939";
	//private String orderTime = dateformat.format(Calendar.getInstance()
		//	.getTime());
	@Resource
	private FundsConfig fundsConfig;
	@Resource
	private BaofuConfig baofuConfig;
	@Resource
	private ProducerService producerService;
	
	@Resource
	private ActiveMQTopic rechargeSucceseDestination;
	
	@RequestMapping(value = "/recharge/applyPayment")
	public RedirectView applyPayment(@RequestParam Long id,
			ModelMap modelMap, HttpServletRequest request,
			HttpServletResponse response) {

		P2PRecharge p2pRecharge = p2pRechargeService.findP2PRechargeById(id);

		
		Money orderMoney = p2pRecharge.getMoney();
		
		
		modelMap.addAllAttributes(baofuConfig.getApplyParams());
		modelMap.addAttribute(BaofuConfig.BaofuApplyKey.OrderMoney.name(), orderMoney.getCent());
		modelMap.addAttribute(BaofuConfig.BaofuApplyKey.TradeDate.name(), dateformat.format(p2pRecharge.getAddTime()));
		modelMap.addAttribute(BaofuConfig.BaofuApplyKey.TransID.name(), p2pRecharge.getId());
		modelMap.addAttribute(BaofuConfig.BaofuApplyKey.Signature.name(), getApplySign(modelMap,baofuConfig.getKey()));
	//	Object o = modelMap.get(BaofuConfig.BaofuApplyKey.PayID.name());
		
		
		return new RedirectView(baofuConfig.getPayUrl(), true,
				false, true);
	}
	
	@LoginNeedless
	@RequestMapping(value = "/receivePayment", method = RequestMethod.POST)
	public void receivePayment(HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam Map<String,String> receivePaymentModel) {
		System.out.println("receivePayment  xxxx");
		System.out.println(receivePaymentModel);
		StringBuilder sb = new StringBuilder();
		String sign = getReturnSign(receivePaymentModel,this.baofuConfig.getKey());
		System.out.println("sing="+sign);
		String receiveSign = receivePaymentModel.get(BaofuConfig.BaofuReceiveKey.Md5Sign.name());
		String baofuResult = receivePaymentModel.get(BaofuConfig.BaofuReceiveKey.Result.name());
		
		
		if(StringUtils.equals(sign, receiveSign)&&StringUtils.equals(baofuResult, "1")){
			String idstr = receivePaymentModel.get(BaofuConfig.BaofuReceiveKey.TransID.name());
			String orderMoney = receivePaymentModel.get(BaofuConfig.BaofuReceiveKey.FactMoney.name());
			Money returnOrderMoney = new Money(Long.valueOf(orderMoney));
			Long rechargeId = Long.valueOf(idstr);
			
			P2PRecharge p2pRecharge = p2pRechargeService
					.findP2PRechargeById(rechargeId);
			if(p2pRecharge.getStatus()!=11){
				returnMessage(response, "OK");
				return;
			}
			//P2PRecharge p2pRecharge = p2pRechargeService.findP2PRechargeById(id);
			// 金额的比较
			if (p2pRecharge.getMoney().getCent()==returnOrderMoney.getCent()) {
				p2pRecharge.setStatus(P2PRecharge.Status.SUCCESS.getStatus());
				p2pRecharge.setOutTransNo("");
				p2pRecharge.setUpTime(Calendar.getInstance().getTimeInMillis());
				p2pRecharge.setOkTime(Calendar.getInstance().getTimeInMillis());
				p2pRecharge.setUpIp(getRemoteIp(request));
				p2pRechargeService.updateP2PRecharge(p2pRecharge);
				/*
				 * P2PRechargeReturn p2pRechargeReturn = new
				 * P2PRechargeReturn();
				 * p2pRechargeReturn.setRid(Long.valueOf(TransNo));
				 * p2pRechargeReturn
				 * .setUpTime(Calendar.getInstance().getTimeInMillis());
				 * p2pRechargeReturn
				 * .setStatus(P2PRechargeReturn.Status.HIDDEN.getStatus());
				 * p2pRechargeReturnService
				 * .saveP2PRechargeReturn(p2pRechargeReturn);
				 */

				String userAccountNo = p2pRecharge.getTradeAccount();

				if (StringUtils.isNoneBlank(userAccountNo)) {
					TransInfo transInfo = new TransInfo();

					// 充值账号
					transInfo.setTransAccountIn(userAccountNo);
					// 总帐总帐账号
					transInfo.setTransAccountOut(InnerAccountConsts.innerTotalAccountNo);
					//Long money = (long) (p2pRecharge.getMoney() * 100);

					

					// 充值金额
					transInfo.setTransAmount(new Money(p2pRecharge.getMoney().getCent()));
					// 充值做帐
					transInfo.setTransOutOrderNo(String.valueOf(rechargeId));
					System.out.println("transAmount="+transInfo.getTransAmount());
					AccountTransResult result = accountTransFacade
							.doDeposit(transInfo);
					if (!result.isSuccess()) {
						logger.error("accountTransFacade.doDeposit error,code="
								+ result.getResultCode());
					}else{
						this.sendNotify(p2pRecharge);
					}
				} else {
					logger.error("user accountNo not exit");
				}

				returnMessage(response, "OK");
			}
		}
		
	}
	/**
	 * 将交易关键数据进行拼接，经 MD5 加密生成
	 * 并转化为小写的 32 位加密字符串。
	 * 规则如下：
	 * {参数}代表参数的具体值
	 * MD5({MerchantID}|{PayID}|{TradeDate}|{
	 * TransID}|{OrderMoney}|{PageUrl}|{Retur
	 * nUrl}|{NoticeType}|{密钥})
	 * 测试密钥： abcdefg
	 * 
	 */
	public static String getApplySign(ModelMap modelMap,String key){
		StringBuilder sb = new StringBuilder();
		sb.append(modelMap.get(BaofuConfig.BaofuApplyKey.MemberID.name())+"|");
		sb.append(modelMap.get(BaofuConfig.BaofuApplyKey.PayID.name())+"|");
		sb.append(modelMap.get(BaofuConfig.BaofuApplyKey.TradeDate.name())+"|");
		sb.append(modelMap.get(BaofuConfig.BaofuApplyKey.TransID.name())+"|");
		sb.append(modelMap.get(BaofuConfig.BaofuApplyKey.OrderMoney.name())+"|");
		sb.append(modelMap.get(BaofuConfig.BaofuApplyKey.PageUrl.name())+"|");
		sb.append(modelMap.get(BaofuConfig.BaofuApplyKey.ReturnUrl.name())+"|");
		sb.append(modelMap.get(BaofuConfig.BaofuApplyKey.NoticeType.name())+"|");
		sb.append(key);
		String MD5Result = MD5Util.md5(sb.toString()).toLowerCase();
		return MD5Result;
		

	}
	
	/**
	 * 
	 * MD5(MemberID={MemberID}~|~TerminalID={Termi
	 * nalID}~|~TransID={TransID}~|~Result={Result
	 * }~|~ResultDesc={ResultDesc}~|~FactMoney={Fa
	 * ctMoney}~|~AdditionalInfo={AdditionalInfo}~
	 * |~SuccTime={SuccTime}~|~Md5Sign={密钥})
	 * 测试密钥： abcdefg
	 * 
	 * 
	 */
	public static String getReturnSign(Map<String,String> map,String key){
		StringBuilder sb = new StringBuilder();
		sb.append(BaofuConfig.BaofuReceiveKey.MemberID.name()+"="+map.get(BaofuConfig.BaofuReceiveKey.MemberID.name())+"~|~");
		sb.append(BaofuConfig.BaofuReceiveKey.TerminalID.name()+"="+map.get(BaofuConfig.BaofuReceiveKey.TerminalID.name())+"~|~");
		sb.append(BaofuConfig.BaofuReceiveKey.TransID.name()+"="+map.get(BaofuConfig.BaofuReceiveKey.TransID.name())+"~|~");
		sb.append(BaofuConfig.BaofuReceiveKey.Result.name()+"="+map.get(BaofuConfig.BaofuReceiveKey.Result.name())+"~|~");
		sb.append(BaofuConfig.BaofuReceiveKey.ResultDesc.name()+"="+map.get(BaofuConfig.BaofuReceiveKey.ResultDesc.name())+"~|~");
		sb.append(BaofuConfig.BaofuReceiveKey.FactMoney.name()+"="+map.get(BaofuConfig.BaofuReceiveKey.FactMoney.name())+"~|~");
		sb.append(BaofuConfig.BaofuReceiveKey.AdditionalInfo.name()+"="+map.get(BaofuConfig.BaofuReceiveKey.AdditionalInfo.name())+"~|~");
		sb.append(BaofuConfig.BaofuReceiveKey.SuccTime.name()+"="+map.get(BaofuConfig.BaofuReceiveKey.SuccTime.name())+"~|~");
		sb.append(BaofuConfig.BaofuReceiveKey.Md5Sign.name()+"="+key);
		String MD5Result = MD5Util.md5(sb.toString()).toLowerCase();
		return MD5Result;
		

	}
	private void sendNotify(P2PRecharge p2pRecharge){
		this.producerService.sendMessage(rechargeSucceseDestination, p2pRecharge);
	}
	
}
